package com.hksj.Intelligentmanagement.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @ClassName ExportExcel
 * @Author zengke
 * @Date 2023/7/24 15:05
 */

public class ExportExcel {

    //导出指定模板的excel表格
    public static void export(String path, int skipRow, Iterable<?> data, HttpServletResponse response){

        File file = new File(path);

        //获取写对象
        ExcelWriter writer = ExcelUtil.getWriter();

        //设置单元格自动换行
        writer.getCellStyle().setWrapText(true);

        //跳过行数
        writer.passRows(skipRow);

        //不输出表头
        writer.write(data,false);

        //导出
        ServletOutputStream out = null;
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode("test","utf-8"));
            response.setCharacterEncoding("UTF-8");
            out = response.getOutputStream();
            writer.flush(out, true);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            writer.close();
            IoUtil.close(out);
            FileUtil.del(file);
        }

    }


}
